package gameClient.thread;

import com.alibaba.fastjson.JSON;
import gameClient.model.Message;
import gameClient.view.ClientMainFrame;

/**
 * 实现计时器线程
 */
public class CountThread extends Thread {
    private int index;
    private ClientMainFrame clientMainFrame;
    private boolean isRun;

    public boolean isRun() {
        return isRun;
    }

    public void setRun(boolean run) {
        isRun = run;
    }

    public CountThread(int index, ClientMainFrame clientMainFrame) {
        this.index = index;
        this.clientMainFrame = clientMainFrame;
        isRun = true;
    }

    @Override
    public void run() {
        while (index >= 0 && isRun) {
            clientMainFrame.timeLabel.setText(String.valueOf(index));
            index--;

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Message message = null;
        //倒计时结束或者不抢地主
        if (index == -1 || (!isRun && !clientMainFrame.isLord)) {
            message = new Message(1, clientMainFrame.currentPlayer.getId(), "不抢", null);
        }
        //抢地主了
        if (!isRun && clientMainFrame.isLord) {
            message = new Message(2, clientMainFrame.currentPlayer.getId(), "抢地主", null);
        }
        //发送消息到服务器
        clientMainFrame.sendThread.setMessage(JSON.toJSONString(message));
    }
}
